#include "rndis.h"
#include "configargs.h"
#include "hardinterfacetest/hardinterfacetest.h"
#include <QFile>
#include <stdlib.h>
#include <stdio.h>


rndis::rndis(QWidget *parent) : JDialog(parent)
{
    QGridLayout *mainHLayout = new QGridLayout(this);
    QGridLayout *pSubLayout = new QGridLayout;
    QVBoxLayout *VBoxLayout = new QVBoxLayout;


    pFrame = new QFrame(this);
    process = new QProcess(this);
    initLabel();

    VBoxLayout->addWidget(tipsLabel);
    VBoxLayout->addWidget(ubootVersionLabel);
    VBoxLayout->addWidget(kernelVersionLabel);
    VBoxLayout->addWidget(appVersionLabel);
    VBoxLayout->addWidget(libVersionLabel);

    initRetBtn();
    VBoxLayout->addWidget(returnMainWindowBut);

    m_ipaddr.clear();
    m_netmask.clear();
    m_status = "not active";

    pSubLayout->addLayout(VBoxLayout, 0,0,1,1);

    pFrame->setLayout(pSubLayout);

    mainHLayout->addWidget(pFrame, 0, 0, 1, 1);

    pFrame->setObjectName("versionFrame");
    this->setJLayout(mainHLayout);
    this->setJTitle(tr("RNDIS Setting"));


        QString iconQssStr;
        QString sizeQssStr;
        if(g_lcdsize == LCDSIZE_1280x800){
            QFile sizeQss(":/qss/linuxdesktop/stylesheet/subwidgetsize_1024x768.qss");
            QFile iconQss(":/qss/linuxdesktop/stylesheet/subwidgeticon_1024x768.qss");
            sizeQss.open(QFile::ReadOnly);
            sizeQssStr = sizeQss.readAll();

            iconQss.open(QFile::ReadOnly);
            iconQssStr = iconQss.readAll();
        }else if(g_lcdsize == LCDSIZE_1024x768){
            QFile sizeQss(":/qss/linuxdesktop/stylesheet/subwidgetsize_1024x768.qss");
            QFile iconQss(":/qss/linuxdesktop/stylesheet/subwidgeticon_1024x768.qss");
            sizeQss.open(QFile::ReadOnly);
            sizeQssStr = sizeQss.readAll();

            iconQss.open(QFile::ReadOnly);
            iconQssStr = iconQss.readAll();
        }else if(g_lcdsize == LCDSIZE_800x600){
            QFile sizeQss(":/qss/linuxdesktop/stylesheet/subwidgetsize_800x600.qss");
            sizeQss.open(QFile::ReadOnly);
            sizeQssStr = sizeQss.readAll();

            QFile iconQss(":/qss/linuxdesktop/stylesheet/subwidgeticon_800x600.qss");
            iconQss.open(QFile::ReadOnly);
            iconQssStr = iconQss.readAll();
        }else   if(g_lcdsize == LCDSIZE_800x480){
            QFile sizeQss(":/qss/linuxdesktop/stylesheet/subwidgetsize7b.qss");
            sizeQss.open(QFile::ReadOnly);
            sizeQssStr = sizeQss.readAll();
            QFile iconQss(":/qss/linuxdesktop/stylesheet/subwidgeticon7b.qss");
            iconQss.open(QFile::ReadOnly);
            iconQssStr = iconQss.readAll();
        }else   if(g_lcdsize == LCDSIZE_480x272){
            QFile sizeQss(":/qss/linuxdesktop/stylesheet/subwidgetsize_480x272.qss");
            sizeQss.open(QFile::ReadOnly);
            sizeQssStr = sizeQss.readAll();
            QFile iconQss(":/qss/linuxdesktop/stylesheet/subwidgeticon_480x272.qss");
            iconQss.open(QFile::ReadOnly);
            iconQssStr = iconQss.readAll();
        }

    this->setStyleSheet(sizeQssStr + iconQssStr);
    this->show();
    //startSettings();
    connect(this, SIGNAL(signal_finish_setting(int)), this, SLOT(slot_finish_setting(int)));
    QTimer::singleShot(600, this, SLOT(startSettings()));

}
rndis::~rndis()
{
    stopUDHCPD();

    delete ubootVersionLabel;
    delete kernelVersionLabel;
    delete appVersionLabel;
    delete libVersionLabel;
    delete tipsLabel;

    delete process;
    delete pFrame;
}

void rndis::initLabel()
{
    int retCnt1;
    int retCnt2;

    tipsLabel = new QLabel(this);
    ubootVersionLabel = new QLabel(this);
    kernelVersionLabel = new QLabel(this);
    appVersionLabel = new QLabel(this);
    libVersionLabel = new QLabel(this);
    //this->setAttribute(Qt::WA_DeleteOnClose);
    qDebug("%s[%d]***", __FUNCTION__, __LINE__);

    tipsLabel->setText(tr("正在设定网络，请稍后......"));
    ubootVersionLabel->setText(tr("RNDIS host IP：")+"????");
    kernelVersionLabel->setText(tr("RNDIS netmask：")+"????");
    appVersionLabel->setText(tr("status：")+"????");

    tipsLabel->setAlignment(Qt::AlignCenter);
    ubootVersionLabel->setAlignment(Qt::AlignCenter);
    kernelVersionLabel->setAlignment(Qt::AlignCenter);
    appVersionLabel->setAlignment(Qt::AlignCenter);
    libVersionLabel->setAlignment(Qt::AlignCenter);

}

void rndis::initRetBtn()
{
    returnMainWindowBut = new QPushButton(this);
    returnMainWindowBut->setText(tr("  退出  "));
    connect(returnMainWindowBut, SIGNAL(released()), this, SLOT(close()));
}

int rndis::getRNDISIPAndMask()
{
    QStringList tmpList;
    QString tmp;
    int cnt=0;
    qDebug("%s[%d]***: ", __FUNCTION__, __LINE__);
    process->start("ifconfig usb0 192.168.100.1 netmask 255.255.255.0 up");
    process->waitForStarted();
    process->waitForFinished(5000);

    qDebug("%s[%d]***: ", __FUNCTION__, __LINE__);
    process->start("ifconfig usb0");
    process->waitForStarted();
    process->waitForFinished(5000);
    tmp = QString(process->readAll());
    tmpList = tmp.remove(QRegExp("\x20")).split("\n");
    qDebug("%s[%d]***: ", __FUNCTION__, __LINE__);
    foreach (QString str, tmpList) {
        if(str.contains("inetaddr:")){
            m_ipaddr = parseString(str, "inetaddr:", "Bcast:");
            qDebug("%s[%d]***: ipaddr:%s", __FUNCTION__, __LINE__, qPrintable(m_ipaddr));
            cnt++;
        }
        if(str.contains("Mask:")){
            m_netmask = parseString(str, "Mask:", "");
            qDebug("%s[%d]***: mask:%s", __FUNCTION__, __LINE__, qPrintable(m_netmask));
            cnt++;
        }
    }
    return cnt;
}


int rndis::getStatus()
{
    QString tmpStr;
    int ret;
    ret = -1;
    process->start("cat /sys/class/net/usb0/carrier");
    process->waitForStarted();
    process->waitForFinished(5000);
    tmpStr = QString(process->readAll());
    m_status.clear();

    if(tmpStr.size() > 2 && tmpStr.contains("error"))
    {
        qDebug("%s[%d]***: status err:%s", __FUNCTION__, __LINE__, qPrintable(tmpStr));
        return -1;
    }else{
        if(tmpStr.toInt() == 0){
            m_status = "disabled";
            ret = 0;
        }else if(tmpStr.toInt() == 1){
            m_status = "enabled";
            ret = 1;
        }else{
            m_status.sprintf("Unknow Status:%d", tmpStr.toInt());
            ret = tmpStr.toInt();
        }
        qDebug("%s[%d]***: status num:%s", __FUNCTION__, __LINE__, qPrintable(tmpStr));
    }
    return ret;
}

int rndis::startUDHCPD()
{
    process->start("touch /var/lib/misc/udhcpd.leases");
    process->waitForStarted();
    process->waitForFinished(5000);
    qDebug("%s[%d]***", __FUNCTION__, __LINE__);

    process->start("udhcpd -f /etc/udhcpd.conf &");
    process->waitForStarted();
    process->waitForFinished(9000);
}

int rndis::stopUDHCPD()
{
    qDebug("%s[%d]***", __FUNCTION__, __LINE__);
    process->start("killall -9 udhcpd");
    process->waitForStarted();
    if(!process->waitForFinished(5000)){
        system("killall -9 udhcpd");
    }
    qDebug("%s[%d]***", __FUNCTION__, __LINE__);
    process->start("ifconfig usb0 down");
    process->waitForStarted();
    if(!process->waitForFinished(5000)){
        system("ifconfig usb0 down");
    }
}

void rndis::startSettings()
{
    int retCnt1;
    int retCnt2;

    retCnt1 = getRNDISIPAndMask();
    if(retCnt1 <= 0){
        QMessageBox::critical(this,"Error",tr("获取RNDIS IP出现错误，错误码：")+QString().sprintf("%d", retCnt1));
    }

    retCnt2 = getStatus();
    if(retCnt2 < 0){
        QMessageBox::critical(this,"Error",tr("获取RNDIS Status出现错误，错误码：")+QString().sprintf("%d", retCnt2));
    }
    tipsLabel->setText(tr("网络设定完毕。"));
    qDebug("%s[%d]***", __FUNCTION__, __LINE__);
    ubootVersionLabel->setText(tr("RNDIS host IP：")+m_ipaddr);
    kernelVersionLabel->setText(tr("RNDIS netmask：")+m_netmask);
    appVersionLabel->setText(tr("status：")+m_status);

    qDebug("%s[%d]***", __FUNCTION__, __LINE__);

    if(retCnt1 > 0 || retCnt2 > 0){// must be ar logic! some time carrier is always 0
        startUDHCPD();
    }

    emit signal_finish_setting(retCnt1+retCnt2);
}

QString rndis::parseString(const QString &srcStr, const QString &beginStr, const QString &endStr)
{
    if(endStr.isEmpty()){
        //qDebug("%s[%d]--: ", __FUNCTION__, __LINE__);
        if(srcStr.contains(beginStr)){
            //qDebug("%s[%d]--: ", __FUNCTION__, __LINE__);
            return srcStr.right(srcStr.length() - srcStr.indexOf(beginStr) - beginStr.length());
        }else{
            //qDebug("%s[%d]--: ", __FUNCTION__, __LINE__);
            return NULL;
        }
    }else{
        //qDebug("%s[%d]--: ", __FUNCTION__, __LINE__);
        if(srcStr.contains(beginStr) && srcStr.contains(endStr)){
            //qDebug("%s[%d]--: ", __FUNCTION__, __LINE__);
            return srcStr.mid(srcStr.indexOf(beginStr) + beginStr.length(),
                              srcStr.indexOf(endStr) - srcStr.indexOf(beginStr) - beginStr.length());
        }else{
            //qDebug("%s[%d]--: ", __FUNCTION__, __LINE__);
            return NULL;
        }
    }
}

//QString rndis::getKernelVersion()
//{
//    process->start("/bin/sh /etc/get_kernel_version.sh");
//    process->waitForStarted();
//    process->waitForFinished(5000);
//    QString procResult = process->readLine();
//    return procResult;
//}

//QString rndis::getUbootVersion()
//{
//    process->start("/bin/sh /etc/get_uboot_version.sh");
//    process->waitForStarted();
//    process->waitForFinished(5000);
//    QString procResult = process->readLine();
//    return procResult;
//}

void rndis::slot_return()
{
    stopUDHCPD();
    close();
}

void rndis::slot_finish_setting(int param)
{
    this->update();
}
